#include "driver/ledc.h"
#include "esp_err.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"

static uint32_t current_duty = 8191;

void ledc_set_duty(ledc_channel_t channel, uint32_t duty)
{
    ESP_ERROR_CHECK(ledc_set_duty(LEDC_LOW_SPEED_MODE, channel, duty));
    ESP_ERROR_CHECK(ledc_update_duty(LEDC_LOW_SPEED_MODE, channel));
}

void ledc_channel_init(int gpio_num, ledc_channel_t channel)
{
    // 2. 配置通道
    ledc_channel_config_t ledc_channel = {
        .gpio_num       = gpio_num,             // GPIO号
        .speed_mode     = LEDC_LOW_SPEED_MODE, // C3只有 low speed
        .channel        = channel,              // 通道0
        .intr_type      = LEDC_INTR_DISABLE,    // 不使用中断
        .timer_sel      = LEDC_TIMER_0,        // 选择定时器0
        .duty           = current_duty,         // 初始占空比为8191 (0~8191)
        .hpoint         = 0,                     // 占空比变化时刻为0
    };
    ESP_ERROR_CHECK(ledc_channel_config(&ledc_channel));
}

void ledc_task(void *arg){
    // while (1) {
    //     // 在这里执行LED控制任务
    //     vTaskDelay(pdMS_TO_TICKS(1000)); // 每秒执行一次
    //     current_duty -= 1000;

    //     if(current_duty < 0 || current_duty > 8191){
    //         current_duty = 8191;
    //     }
    //     printf("Current duty: %ld\n", current_duty);
    //     ledc_set_duty(LEDC_CHANNEL_0, current_duty);
    // }

    ESP_ERROR_CHECK(ledc_fade_func_install(0));

     while (1) {
        // 渐亮
        ESP_ERROR_CHECK(ledc_set_fade_with_time(
            LEDC_LOW_SPEED_MODE, LEDC_CHANNEL_0, 0, 4000));
        ESP_ERROR_CHECK(ledc_fade_start(
            LEDC_LOW_SPEED_MODE, LEDC_CHANNEL_0, LEDC_FADE_WAIT_DONE));

        vTaskDelay(pdMS_TO_TICKS(2000));

        // 渐暗
        ESP_ERROR_CHECK(ledc_set_fade_with_time(
            LEDC_LOW_SPEED_MODE, LEDC_CHANNEL_0, 8191, 4000));
        ESP_ERROR_CHECK(ledc_fade_start(
            LEDC_LOW_SPEED_MODE, LEDC_CHANNEL_0, LEDC_FADE_WAIT_DONE));

        vTaskDelay(pdMS_TO_TICKS(2000));
    }
}

void ledc_init(void)
{
    // 1. 配置定时器
    ledc_timer_config_t ledc_timer = {
        .speed_mode       = LEDC_LOW_SPEED_MODE, // C3只有 low speed
        .duty_resolution  = LEDC_TIMER_13_BIT,   // 分辨率 13位 (0~8191)
        .timer_num        = LEDC_TIMER_0,        // 定时器0
        .freq_hz          = 5000,                // PWM频率 5 kHz
        .clk_cfg          = LEDC_AUTO_CLK        // 自动选择时钟
    };
    ESP_ERROR_CHECK(ledc_timer_config(&ledc_timer));

    ledc_channel_init(GPIO_NUM_8, LEDC_CHANNEL_0);

    xTaskCreate(ledc_task, "ledc_task", 2048, NULL, 5, NULL);
}

void ledc_stop(ledc_channel_t channel)
{
    ESP_ERROR_CHECK(ledc_stop(LEDC_LOW_SPEED_MODE, channel, 0));
}